Angular Decorators

    Decorators

    In Angular applications, decorators are design patterns or functions that change the definition of a class without changing its implementation. They are prefixed by the `@` symbol.

    If you don’t understand the definition then it's fine, we will be going through the types of decorators in Angular, which ultimately will clear its purpose.

    Class decorator

    Class decorators are used to defining the intent of the classes. There are two types of class decorators:

    1. @Component

    This decorator informs the compiler that the given class is a component. It will also bind the selector and template, which will further help the compiler to fetch the HTML and selector.

    In the example below, MyFirstComponent is declared as a component by the @Component declarator. A code example is given below.

    import { NgModule, Component } from '@angular/core';
    
    @Component({
      selector: 'my-first-component',
      template: '<div> Hello techgeekbuzz!</div>',
    })
    
     
    export class MyFirstComponent {
      constructor() {
      //code here
      }
    }

    1. @NgModule

    This declarator informs the compiler that the given class is a Module. We will go through a detailed explanation of components and Modules as we go through this course. Although Angular v14 has abolished the use of @NgModule, it will still be better to understand this concept.

    In the example below, @NgModule helps the compiler to interpret that the given class is a module. Observe how both classes by themselves are effectively the same. No code is needed within the class to tell Angular that it is a component or a module. All we need to do is decorate it, and Angular will do the rest.

    @NgModule({
      imports: [],
      declarations: [],
    })
    
    export class ExampleModule {
      constructor() {
        console.log('Hey I am a module!');
      }
    }


    Property Decorator

    There are two types of property decorators in Angular:

    1. @Input

    @Input decorator informs that the variable ahead is an input to the current component. Following is an example where a variable is passed to the component, and furthermore, that variable is declared inside the class with the @Input decorator.

    export class MyFirstComponent {
    
      @Input() message: string;
    
    }
    
    
    <my-first-component [message]="Hello">
    
    </my-first-component>

    1. @Output

    @Output decorator informs that the variable ahead is output to the current component. This means that this variable will be going out of the current component. The declaration and code syntax is exactly the same as of @Input decorator.